In Svelte, the afterUpdate lifecycle hook runs immediately after the DOM has been updated following a state or prop change. This is useful for running code that depends on the updated DOM, such as DOM measurements, animations, or integrating with third-party libraries.
Running animations or transitions after the DOM changes.
Measuring DOM elements after they have been rendered or resized.
Integrating third-party libraries that need access to the updated DOM.
Debugging by checking the final state of the DOM after reactivity updates.
In this example, afterUpdate logs the count after the DOM has been updated. When you click the button, the log appears right after the <h1> element updates.
Here, afterUpdate ensures that we measure the paragraph element after it has been rendered with the latest text, avoiding inaccurate measurements.
afterUpdate runs after the DOM has been updated.
It is ideal for measuring DOM elements or triggering animations.
It runs every time a reactive update occurs.
For logic that needs to happen before the DOM changes, use beforeUpdate instead.